import { createRouter, createWebHistory } from 'vue-router';
import Login from '../views/Login.vue';
import Dashboard from '../views/Dashboard.vue';
import Unauthorized from '../views/Unauthorized.vue';

const routes = [
  { path: '/', component: Login }, // 首页显示登录页面
  {
    path: '/dashboard',
    component: Dashboard,
    meta: { requiresAuth: true } // 需要认证
  },
  { path: '/unauthorized', component: Unauthorized } // 未授权页面
];

const router = createRouter({
  history: createWebHistory(),
  routes
});

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token'); // 从 localStorage 获取 token

  if (to.meta.requiresAuth && !token) {
    // 如果路由需要认证且用户未登录，跳转到登录页面
    next('/');
  } else if (to.path === '/' && token) {
    // 如果用户已经登录并尝试访问登录页面，自动跳转到 Dashboard
    next('/dashboard');
  } else {
    // 否则，允许访问
    next();
  }
});

export default router;